package com.stdz.counter.core.thread;

import com.stdz.counter.core.cache.MeterInfoCache;
import com.stdz.counter.core.pool.ClientPool;
import com.stdz.counter.core.pool.SyncThreadPool;
import com.stdz.counter.entity.MeterInfo;
import com.stdz.counter.utils.ParamHelper;
import com.stdz.counter.utils.ResourceUtil;
import de.re.easymodbus.modbusclient.ModbusClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 *
 */
public class SyncTaskDispatcherThread implements Runnable {

    private static transient Logger logger = LoggerFactory.getLogger(SyncTaskDispatcherThread.class);

    private static int span = 0;

    public SyncTaskDispatcherThread() {
        ResourceUtil.autowired(this);
    }

    public void run() {
        span++;
        int syncSpan = ParamHelper.getParamIntVal("sync_span", 30);
        if (span < syncSpan) {
            span++;
            return;
        } else {
            span = 0;
        }
        logger.info("task dispatcher thread run start");
        try {
            this.dispatcher();
        } catch (Throwable t) {
            logger.error("task dispatcher run exception:", t);
        }
        logger.info("task dispatcher thread run end");
    }

    private void dispatcher() {
        List<String> comPorts = MeterInfoCache.getInstance().getComPorts();
        if (comPorts != null && comPorts.size() > 0) {
            for (String comPort : comPorts) {
                try {
                    this.dispatcherComSyncTask(comPort);
                } catch (Throwable t) {
                    logger.error("dispatcher com:{} task error:", new Object[]{comPort});
                    logger.error("dispatcher com task exception:", t);
                }
            }

        }
    }

    private void dispatcherComSyncTask(String comPort) {
        List<MeterInfo> meterInfos = MeterInfoCache.getInstance().getComMeterInfos(comPort);
        if (meterInfos == null || meterInfos.size() == 0) {
            return;
        }
        SyncThreadPool.submit(comPort, meterInfos);
    }
}
